from django.db.models import Q
from django.utils import timezone
from django.views import View
import json
from houses.models import House, HouseImage
from django.http import  JsonResponse
from i_home.utils.view import LoginRequiredMixin
from order.models import Order
import datetime
import time



#构造计算日期差函数
def Subtime(date1,date2):
        #格式化时间
        date1 = time.strptime(date1,"%Y-%m-%d")
        date2 = time.strptime(date2,"%Y-%m-%d")

        #判断一下需要减的是哪一个部位
        date1 =datetime.datetime(date1[0],date1[1],date1[2])

        date2 = datetime.datetime(date2[0], date2[1], date2[2])

        return (date2 - date1).days

class CommentsView(LoginRequiredMixin, View):
    def put(self, request, order_id):
         # 接收参数
        json_dict = json.loads(request.body)
        comment = json_dict.get('comment')
         # 校验参数
        try:
             order = Order.objects.get(id=order_id)
        except Exception as e:
            return JsonResponse({'errno': 4002,
                                 'errmsg': 'NODATA'})
         # 判断房东订单状态是否待评价
        if order.status!=3:
            return JsonResponse({'errno': 4004,
                                 'errmsg': 'DATAERR'})
        # 将评论信息写到数据库
        order.comment = comment
        order.status = 4
        # order.end_date= timezone.localtime(order.create_time).strftime("%Y-%m-%d")
        order.save()
        # 返回前端
        return JsonResponse({'errno': '0',
                             'errmsg': '评论成功'})



# 添加订单
class AddOrderView(LoginRequiredMixin, View):

        def post(self,request):

            #接受参数
            dict =json.loads(request.body.decode())
            house_id = dict.get('house_id')
            begin_date = dict.get('start_date')
            end_date = dict.get('end_date')
            day = Subtime(begin_date,end_date)

            #校验参数
            if not all([begin_date,end_date,house_id]):
                return JsonResponse({'errno':4103,
                                        'errmsg':'缺少参数'})

            try:
                house = House.objects.get(id = house_id)

            except  Exception as e:

              return JsonResponse({'errno':4001,
                                        'errmsg':'查询信息有误'})

            data ={}
            #判断登录用户是否是发布房源的房东
            if request.user == house.user:
                return JsonResponse({
                    'errno':4004,
                    'errmsg':'不可以查看自己发布的房源'})

            #查询满足要求的房源订单
            try:

                # orders =Order.objects.filter(house = house, status__in=[0, 1, 2], end_date__gt=begin_date)
                orders = Order.objects.filter(house=house, begin_date__lt=end_date, end_date__gt=begin_date,status__in=[0, 1, 2])


            except Exception  as e:
                return JsonResponse({'errno': 4001,
                                         'errmsg': '查询信息有误'})


            if orders:

                return JsonResponse({'errno': 4001,
                                     'errmsg': '该房源已经被预定'})


            try:
                order = Order.objects.create(
                    house_id = house_id,
                    begin_date =begin_date,
                    end_date =end_date,
                    user =request.user,
                    house =house,
                    days = day,
                    house_price =int(house.price),
                    amount = day*int(house.price),
                    status = 0,
                         )

            except Exception  as e:
                    return JsonResponse({'errno': 4004,
                                    'errmsg': '创建失败'})

            #每提交一个订单，预定订单数+1
            try:
                house.order_count +=1
                house.save()

            except Exception  as e:
                return JsonResponse({'errno': 4004,
                                     'errmsg': '保存失败'})


                 #构建返回数据

            data['order_id'] = order.id
            return JsonResponse({'errno': 0,
                                'errmsg': 'ok',
                                'data':data })




        def get(self,request):#获取订单

                role =request.GET.get('role')
                list =[]

                #判断用户类别
                #如果是房客
                if role == 'custom':

                #从订单表中找到用户的订单
                    try:
                        orders =Order.objects.filter(user = request.user).order_by("-create_time")

                    except Exception as e:

                        return JsonResponse({'errno': 4001,
                                             'errmsg': '查询信息有误'})
                #如果是房东
                elif role == 'landlord':

                    try:
                        houses = House.objects.filter(user=request.user)
                        orders = Order.objects.filter(house__in=houses).order_by("-create_time")
                    except Exception as e:

                        return JsonResponse({'errno': 4001,
                                             'errmsg': '查询信息有误'})



                for order in orders:
                    if order.status == 1:
                        if role == 'landlord':

                            order.status = 0
                        else:
                            order.status = 1
                    else:
                        list.append({
                            'amount': order.amount,
                            'comment': order.comment,
                            'ctime': timezone.localtime(order.create_time).strftime("%Y-%m-%d %H:%M:%S"),
                            'days': order.days,
                            'start_date': order.begin_date,
                            'end_date': order.end_date,
                            'status': order.status,
                            'title': order.house.title,
                            'img_url': str(order.house.index_image_url),
                            'order_id': order.id
                        })

                    #构造返回数据
                data ={}
                data['orders'] = list

                return JsonResponse({'errno':0,
                                     'errmsg':'ok',
                                     'data':data})


#接单或拒单

class OrderChoice(LoginRequiredMixin, View):

    def put(self, request, order_id):
        #接受校验参数
        dict = json.loads(request.body)
        action = dict.get('action')
        reason = dict.get('reason')
        if not all([action, order_id]):
            return JsonResponse({
                'errno': 4103,
                'errmsg': '参数错误'
            })

        #如果点击的是接受按钮，执行如下操作
        if action == 'accept':
            try:
                order = Order.objects.get(id=order_id)
                order.status = 3
                order.save()
            except Exception as e:
                return JsonResponse({'errno': 4001,
                                     'errmsg': "查询更新有误"})


        #如果点击的是拒绝，写明拒绝原因
        elif action == 'reject':
            if not all([reason]):
                return JsonResponse({'errno': 4001,
                                     'errmsg': '拒单原因参数错误'})
            try:
                order = Order.objects.get(id=order_id)
                order.comment = reason
                order.status = 6
                order.save()
            except Exception as e:

                return JsonResponse({'errno': 4001, 'errmsg': '数据库查询更改失败失败'})

            # try:
            #     house = House.objects.get(id=order.house.id)
            #     if house.order_count >= 1:
            #         house.order_count -= 1
            #     house.save()
            #
            # except Exception as e:
            #     return JsonResponse({'errno': 4001,
            #                          'errmsg': '保存失败'})

            else:
                return JsonResponse({'errno': 4004,
                                     'errmsg': '数据有误'})
        return JsonResponse({'errno': 0,
                                'errmsg': '操作成功'})



